package com.bxj.mybatis.generator.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.exception.ShellException;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.util.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by baixiujiang on 17/10/11.
 */
public class MybatisUtils {
    public static String getTableProperties(IntrospectedTable introspectedTable, String name, String defaultValue) {
        return introspectedTable.getTableConfigurationProperty(name) != null ? introspectedTable.getTableConfigurationProperty(name) : defaultValue;
    }

    public static Boolean getTableProperties(IntrospectedTable introspectedTable, String name, Boolean defaultValue) {
        String check = introspectedTable.getTableConfiguration().getProperty(name);
        return StringUtils.isEmpty(check) ? defaultValue : "true".equals(check);
    }

    public static Boolean getContextProperties(IntrospectedTable introspectedTable, String name, Boolean defaultValue) {
        String check = introspectedTable.getContext().getProperty(name);
        return StringUtils.isEmpty(check) ? defaultValue : "true".equals(check);
    }

    public static Boolean getContextProperties(IntrospectedTable introspectedTable, String name) {
        String check = introspectedTable.getContext().getProperty(name);
        return StringUtils.isEmpty(check) ? null : "true".equals(check);
    }

    /**
     * @param introspectedTable
     * @param targetProject
     * @param targetPackage
     * @param shortName
     * @return true=替换  false=不替换
     */
    public static boolean checkReplaceIfExists(IntrospectedTable introspectedTable, String targetProject, String targetPackage, String shortName) {
        Boolean replaceIfExists = MybatisUtils.getContextProperties(introspectedTable, "replaceIfExists");
        if (replaceIfExists == null)
            replaceIfExists = MybatisUtils.getTableProperties(introspectedTable, "replaceIfExists", false);
        DefaultShellCallback shellCallback = new DefaultShellCallback(false);
        File mapperDir = null;
        try {
            mapperDir = shellCallback.getDirectory(targetProject, targetPackage);
            boolean exists = new File(mapperDir, shortName).exists();
            if (!exists || replaceIfExists)
                return true;
        } catch (ShellException e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }

    public static <T extends JavaElement> void addJavaDocLines(T t) {
        t.addJavaDocLine("/**");
        t.addJavaDocLine(" * 由MyBatis Generator工具自动生成 " + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()));
        t.addJavaDocLine(" */");
    }
}
